// --------------------------------------------------------------------------------------------------------------------
// <copyright file="LiveObjectContainerManager_InternalAppDomain.cs" company="Open Trader">
//   Copyright (c) David Denis (david.denis@systemathics.com)
// </copyright>
// <summary>
//   |  Open Trader - The Open Source Systematic Trading Platform
//   |
//   |  This program is free software: you can redistribute it and/or modify
//   |  it under the terms of the GNU General Public License as published by
//   |  the Free Software Foundation, either version 2 of the License, or
//   |  (at your option) any later version.
//   |
//   |  This program is distributed in the hope that it will be useful,
//   |  but WITHOUT ANY WARRANTY; without even the implied warranty of
//   |  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//   |  GNU General Public License for more details.
//   |
//   |  You should have received a copy of the GNU General Public License
//   |  along with this program.  If not, see http://www.gnu.org/licenses
//   |
//   |  Up to date informations about Open Trader can be found at :
//   |    http://opentrader.org
//   |    http://opentrader.codeplex.com
//   |
//   |  For professional services, please visit us at :
//   |    http://www.systemathics.com
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace Org.OpenTrader.Framework.LiveObjects
{
    #region Usings

    using System;
    using System.Reflection;
    using System.Security.Policy;

    using Org.OpenTrader.Framework.LiveObjects.Interfaces;

    #endregion

    /// <summary>
    /// The live object container manager_ internal app domain.
    /// </summary>
    public class LiveObjectContainerManagerInternalAppDomain : LiveObjectContainerManager
    {
        #region Constructors and Destructors

        /// <summary>
        /// Initializes a new instance of the <see cref="LiveObjectContainerManagerInternalAppDomain"/> class.
        /// </summary>
        /// <param name="desc">
        /// The desc.
        /// </param>
        public LiveObjectContainerManagerInternalAppDomain(ILiveObjectContainerDescriptor desc)
            : base(desc)
        {
        }

        #endregion

        #region Properties

        /// <summary>
        /// Gets or sets Domain.
        /// </summary>
        private AppDomain Domain { get; set; }

        #endregion

        #region Public Methods

        /// <summary>
        /// The create container.
        /// </summary>
        /// <returns>
        /// The create container.
        /// </returns>
        public override bool CreateContainer()
        {
            // Setup the domain to run into the sandbox directory
            var setup = new AppDomainSetup();
            setup.ApplicationBase = this.Descriptor.WorkingDirectory;
            setup.CachePath = this.Descriptor.WorkingDirectory;
            setup.DisallowApplicationBaseProbing = false;
            setup.DisallowBindingRedirects = true;
            setup.DisallowCodeDownload = true;
            setup.DisallowPublisherPolicy = true;

            // TODO : Fine tune evidence with strict security rights
            var evidence = new Evidence(AppDomain.CurrentDomain.Evidence);

            // Create the containing domain
            this.Domain = AppDomain.CreateDomain(this.Descriptor.ID.ToString(), evidence, setup);

            // The domain doesn't expire
            this.Domain.InitializeLifetimeService();

            // We want to create a LiveObjectContainer inside the new domain
            var containerType = typeof(LiveObjectContainer);
            var containerAssemblyName = new AssemblyName(containerType.Assembly.FullName).Name;
            var containerTypeName = containerType.FullName;

            // Ask the domain to make the instance
            this.Container =
                (LiveObjectContainer)
                this.Domain.CreateInstanceAndUnwrap(
                    containerAssemblyName, 
                    containerTypeName, 
                    false, 
                    BindingFlags.Default, 
                    null, 
                    new object[] { }, 
                    null, 
                    null, 
                    evidence);

            this.Container.Initialize(this.Descriptor);

            return true;
        }

        /// <summary>
        /// The destroy container.
        /// </summary>
        /// <returns>
        /// The destroy container.
        /// </returns>
        public override bool DestroyContainer()
        {
            // Call destroy (executed from inside the AppDomain)
            this.Container.Destroy();

            // Unload the domain
            AppDomain.Unload(this.Domain);

            // The container is no more alive
            this.Container = null;

            // Done
            return true;
        }

        #endregion
    }
}